package com.foreveross.proxyip.infra.impl;

import java.sql.Connection;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import org.apache.commons.beanutils.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.foreveross.proxyip.entity.IpStoreEntity;
import com.foreveross.proxyip.entity.IpStoreTmpEntity;
import com.foreveross.proxyip.entity.ProxyIpBean;
import com.foreveross.proxyip.infra.IpstoreRepository;
import com.foreveross.proxyip.infra.base.ddd.repository.EntityHibernateRepository;
import com.foreveross.proxyip.infra.base.ddd.repository.IJdbcRepository;
/**
 * (改用jdbc，实现完全,但还未使用)
 * @author lyq
 *
 */
@Service
public class IpstoreRepositoryImpl  extends EntityHibernateRepository implements IpstoreRepository  {

	@Autowired
	IJdbcRepository jdbcRepository ;

	private final static String INSERT_SQL = "INSERT INTO FDC_PI.PI_IP_STORE \n SELECT * FROM FDC_PI.PI_IP_STORE_TMP T1 WHERE NOT EXISTS(SELECT 1 FROM PI_IP_STORE T2 WHERE T1.IP=T2.IP)";
	/**
	 * 保存源数据
	 * @param list
	 * @return
	 * @throws Exception
	 */
	@SuppressWarnings("rawtypes")
	@Override
	public void transSaveList(List list){
		Connection conn = null;
		boolean currAutoCommit = true;
		try{
			conn = jdbcRepository.getConnection();
			currAutoCommit = conn.getAutoCommit();
			conn.setAutoCommit(false);
			this.jdbcRepository.saveList(conn,list, IpStoreTmpEntity.class);
			this.jdbcRepository.execute(conn, INSERT_SQL);
			this.jdbcRepository.deleteAll(conn, IpStoreTmpEntity.class);
			conn.commit();
		}catch(Exception e){
			logger.info("存入数据出错:" + e);
		}finally{
			try {
				conn.setAutoCommit(currAutoCommit);
				conn.close();
			} catch (Exception e) {
				logger.info("存入数据出错:" + e);
			}
	}
	}
	@SuppressWarnings("rawtypes")
	@Transactional
	public synchronized List dbpoolIpList(Integer num) throws Exception{
		List <ProxyIpBean> resultList = new ArrayList<ProxyIpBean>();
		List<IpStoreEntity> ipstortList = this.queryResult("from IpStoreEntity t order by t.lastTime", null,1,num);
		for(IpStoreEntity ipstore:ipstortList){
			ipstore.setLastTime(new Date());
			ProxyIpBean bean = new ProxyIpBean();
			BeanUtils.copyProperties(bean, ipstore);
			resultList.add(bean);
		}
		return resultList;
	}	
}
